package com.ruoyi.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.api.domain.Merchant;
import com.ruoyi.api.domain.Order;
import com.ruoyi.api.domain.Products;
import com.ruoyi.api.mapper.MerchantMapper;
import com.ruoyi.api.mapper.OrderMapper;
import com.ruoyi.api.mapper.ProductsMapper;
import com.ruoyi.api.service.IMerchantService;
import com.ruoyi.api.vo.MerchantVo;
import com.ruoyi.api.vo.ProductVo;
import com.ruoyi.api.vo.TransactionRecordsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 寻觅
 * @since 2025-05-29
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements IMerchantService {
    @Autowired
    MerchantMapper merchantMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    ProductsMapper productsMapper;

    @Override
    public List<Merchant> selectData() {
        List<Merchant> merchants = merchantMapper.selectData();
        merchants.forEach(merchant -> {
            if (merchant.getRegistrationNumberDate().compareTo(new Date()) <= 0) {
                merchant.setType("已过期");
            } else {
                merchant.setType("有效");
            }
            merchant.setAddress(merchant.getLevelOneName() +
                    " " + merchant.getLevelTwoName() +
                    " " + merchant.getLevelThreeName() +
                    " " + merchant.getLevelFourName() +
                    " " + merchant.getAddress());
        });
        return merchants;
    }

    @Override
    public Merchant info(Long id) {
        Merchant merchant = merchantMapper.getById(id);
        if (merchant.getRegistrationNumberDate().compareTo(new Date()) <= 0) {
            merchant.setType("已过期");
        } else {
            merchant.setType("有效");
        }
        merchant.setAddress(merchant.getLevelOneName() +
                " " + merchant.getLevelTwoName() +
                " " + merchant.getLevelThreeName() +
                " " + merchant.getLevelFourName() +
                " " + merchant.getAddress());
        return merchant;
    }

    @Override
    public List<TransactionRecordsVo> getTransactionRecords(Long id) {
        ArrayList<TransactionRecordsVo> transactionRecordsVos = new ArrayList<>();
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Order::getMerchantId, id);
        List<Order> orders = orderMapper.selectList(orderLambdaQueryWrapper);
        for (Order order : orders) {
            TransactionRecordsVo transactionRecordsVo = new TransactionRecordsVo();
            transactionRecordsVo.setOrderId(order.getOrderId());
            transactionRecordsVo.setMerchantName(order.getMerchantName());
            transactionRecordsVo.setTransactionDate(order.getCreateTime());
            transactionRecordsVo.setStatus(order.getOrderStatus());
            transactionRecordsVo.setQuantity(order.getProductQuantity());
            transactionRecordsVo.setTotalPrice(order.getProductSubtotal());
            transactionRecordsVo.setUserName(order.getUserName());
            transactionRecordsVo.setProductName(productsName(order.getProductId(), order.getProductQuantityOne()));
            transactionRecordsVos.add(transactionRecordsVo);
        }
        return transactionRecordsVos;
    }

    public String productsName(String productIds, String productQuantity) {
        if (productIds == null || productQuantity == null) {
            return null;
        }

        String[] idArray = productIds.split(",");
        String[] quantityArray = productQuantity.split(",");

        // 检查两个数组长度是否一致
        if (idArray.length != quantityArray.length) {
            System.err.println("商品ID数量与商品数量不匹配");
            return null;
        }

        StringBuilder result = new StringBuilder();

        for (int i = 0; i < idArray.length; i++) {
            try {
                // 获取商品ID和数量
                String productId = idArray[i];
                String quantityStr = quantityArray[i];

                ProductVo product = productsMapper.ById(Integer.valueOf(productId));

                if (product != null) {
                    // 拼接商品名称和数量
                    if (result.length() > 0) {
                        result.append(",");
                    }
                    result.append(product.getName()).append("*").append(quantityStr);
                } else {
                    System.err.println("商品ID不存在: " + productId);
                }
            } catch (Exception e) {
                System.err.println("处理商品信息时出错, 索引: " + i + ", 错误: " + e.getMessage());
            }
        }

        return result.toString();
    }

    @Override
    public List<MerchantVo> merchantList() {
        // 最后要返回的数据
        List<MerchantVo> merchantVos = new ArrayList<>();

        // 查询所有商家和商品
        List<Merchant> merchants = merchantMapper.selectListData();
        List<Products> products = productsMapper.selectList(null);

        // 使用Map分组商品，key为商家ID，value为该商家的商品列表
        Map<Long, List<Products>> merchantProductsMap = products.stream()
                .collect(Collectors.groupingBy(Products::getMerchantId));

        // 转换商家数据并关联商品
        for (Merchant merchant : merchants) {
            MerchantVo merchantVo = new MerchantVo();
            BeanUtils.copyProperties(merchant, merchantVo);

            // 获取该商家的商品列表
            List<Products> merchantProducts = merchantProductsMap.getOrDefault(merchant.getId(), Collections.emptyList());
            merchantVo.setProducts(merchantProducts);
            merchant.setAddress(merchant.getLevelOneName() +
                    " " + merchant.getLevelTwoName() +
                    " " + merchant.getLevelThreeName() +
                    " " + merchant.getLevelFourName() +
                    " " + merchant.getAddress());
            merchantVos.add(merchantVo);
        }

        return merchantVos;
    }

}
